/*
销售列表8
*/

<template>
  <div class="app-page">
    <!-- 操作菜单区 -->
    <my-header>
      <el-button type="primary" @click="handleAddUpdate()" v-repeatClick>添加</el-button>
      <el-button @click="handleBeforeUpdate" v-repeatClick>修改</el-button>
      <el-button  v-repeatClick @click="handleCreateInvoice">创建收据</el-button>
      <el-button @click="view" v-repeatClick>查看</el-button>
      <el-button @click="getSaleOrder" v-repeatClick>刷新</el-button>
      <el-button type="danger" @click="delSaleOrder" v-repeatClick>删除</el-button>
    </my-header>

    <!-- 列表区 -->
    <el-card  style="flex: 1;">
      <div class="app-page">
        <div class="content-flex">
          <div>
            <el-form ref="search" :model="search" inline size="small">
              <el-form-item label="" prop="customerNum">
                <el-input
                  placeholder="搜索:客户号"
                  v-model="search.customerNum"
                ></el-input>
              </el-form-item>
              <el-form-item label="" prop="info">
                <el-input
                  placeholder="销售单号/收据号/商品内容/备注"
                  v-model="search.info"
                  style="width: 300px"
                ></el-input>
              </el-form-item>
              <el-form-item label="" prop="status">
                <el-select
                  v-model="search.orderStatus"
                  placeholder="销售单状态"
                >
                  <el-option
                    v-for="item in baseFormOptions.orderStatus"
                    :key="item"
                    :value="item"
                    :label="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="创建日期" prop="date">
                <el-date-picker
                  v-model="search.date"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="" prop="query_batchId">
                <el-button type="primary" round @click="getSaleOrder"
                >搜索</el-button
                >
                <el-button
                  type="warning"
                  round
                  @click="$refs.search.resetFields()"
                >重置</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </div>
        <!-- 列表区 -->
        <div style="flex: 1">
          <el-table
            height="100%"
            :data="data"
            border
            stripe
            highlight-current-row
            ref="multipleTable"
            @row-dblclick="handleRowDbclick"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="index" width="55" align="center">
            </el-table-column>
            <el-table-column type="selection" width="55" align="center">
            </el-table-column>
            <el-table-column label="销售单号" min-width="200">
              <template slot-scope="scope">
                <el-link @click="handleRowDbclick(scope.row)">{{ scope.row.saleOrder.orderCode }} </el-link><span style="margin-left:10px"> {{ scope.row.saleOrder.orderStatus }}</span>
              </template>
            </el-table-column>
            <el-table-column label="收据" min-width="200">
              <template slot-scope="scope">
                <span v-if="scope.row.saleOrder.receiptCode">
                  <el-link>
                    <router-link :to="{path:'/finances/invoice',query:{receiptCode:scope.row.saleOrder.receiptCode}}" target="_blank">
                      {{ scope.row.saleOrder.receiptCode }}</router-link>
                  </el-link>
                  <span style="margin-left:10px"> ({{scope.row.saleOrder.receiptStatus}})</span>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="客户号" min-width="120">
              <template slot-scope="scope">
                <el-link>
                  <router-link :to="{path:'/consumers/customer',query:{customerNum:scope.row.saleOrder.customerNum}}" target="_blank">{{scope.row.saleOrder.customerNum}}</router-link>
                  <span style="margin-left:10px"> {{scope.row.saleOrder.customerName}}</span>
                </el-link>
              </template>
            </el-table-column>
            <el-table-column label="商品内容" width="500">
              <template slot-scope="scope">
                <div v-for="item in scope.row.orderGoods" :key="item.id" class="goods-item">
                  <span style="color: green" v-if="item.goodsCategory == '包邮商品'">包</span>
                  <span style="color: #ff5000" v-else>其他</span>
                  <span>{{item.goodsEnglishBrand}}</span>
                  <span>{{item.goodsName}}</span>
                  <span>{{item.specification}}</span>
                  <span>{{item.buyNum}} × {{item.unitPrice}}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="saleOrder.goodsAmount" label="销售金额"></el-table-column>
            <el-table-column prop="saleOrder.storeName" label="所属门店"></el-table-column>
            <el-table-column
              label="创建时间"
              sortable
              width="200"
              prop="saleOrder.createTime"
              align="center"
            ></el-table-column>
          </el-table>
        </div>
        <!-- 分页区 -->
        <div style="margin-top: 10px">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20, 50, 100, 200, 500, 1000]"
            :page-size="pageSize"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </el-card>
    <!-- 添加修改身份证信息 -->
    <el-dialog
      v-dialog-drag
      :title="title + '销售单'"
      :visible.sync="dialogFormVisible"
      width="1200px"
      :close-on-click-modal="false"
      @close="restForm"
    >
      <el-form
        size="small"
        :model="baseForm"
        label-position="left"
        label-width="100px"
        ref="baseForm"
        :rules="baseRules"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销售单号" prop="orderCode">
              <el-row :gutter="20">
                <el-col :span="14">
                  {{baseForm.orderCode}}
                </el-col>
                <el-col :span="8" v-if="title!=='添加'">
                  收据：FC123456
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="客户号" prop="customerNum">
              <el-input v-model="baseForm.customerNum"></el-input>
            </el-form-item>
            <el-form-item label="商品总金额" prop="goodsAmount">
              <el-input v-model="baseForm.goodsAmount" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="storeName" label="所属门店">
              <el-select
                filterable
                style="width: 100%"
                v-model="baseForm.storeName"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in stores"
                  :key="item.id"
                  :value="item.name"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="状态" prop="orderStatus">
                  <el-select style="width: 100%" v-model="baseForm.orderStatus">
                    <el-option
                      v-for="item in baseFormOptions.orderStatus"
                      :key="item"
                      :value="item"
                      :label="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="总费用" prop="totalAmount">
                  <el-input v-model="baseForm.totalAmount" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="其他杂费" prop="otherAmount" >
              <el-input v-model="baseForm.otherAmount" @change="handleOtherAmount"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="" prop="goodsAmount" label-width="0px">
          <el-input v-model="baseForm.note" placeholder="备注"></el-input>
        </el-form-item>
      </el-form>
      <el-table :data="orderGoods" border style="margin-top:20px">
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button
              type="danger"
              circle
              icon="el-icon-close"
              @click="deleteGoods(scope.$index)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="商品类型"  align="center" width="120">
          <template slot-scope="scope">
            <el-select v-model="scope.row.goodsCategory" @change="handleGoodsCategory(scope.row)">
              <el-option value="包邮商品" label="包邮商品"></el-option>
              <el-option value="其他商品" label="其他商品"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="物品英文品牌" prop="goodsEnglishBrand" >
          <template slot-scope="scope">
            <el-select v-model="scope.row.goodsEnglishBrand" clearable :allow-create="scope.row.goodsCategory === '其他商品'" filterable @focus="handleGoodsTypeChange(scope.row)" @change="handleGoodsChange(scope.row)" no-match-text="搜索中...">
              <el-option v-for="goods in scope.row.goodsList" :key="goods.skuCode" :value="goods.englishBrand">
                <span style="display: inline-block;width:80px">{{goods.skuCode}}</span>
                <span  style="display: inline-block;width:200px">{{goods.goodsName}}</span>
                <span  style="display: inline-block;width:80px">{{goods.englishBrand}}</span>
                <span  style="display: inline-block;width:80px">{{goods.specification}}</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="中文名称" prop="goodsName">
          <template slot-scope="scope">
            <el-input v-model="scope.row.goodsName"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="商品类别" prop="goodsTypeName"  align="center" width="80">
          <template slot-scope="scope">
            <span v-if="scope.row.goodsTypeName !== '新增商品'">{{scope.row.goodsTypeName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="规格型号" prop="specification"  align="center" width="80">
          <template slot-scope="scope">
            <el-input v-model="scope.row.specification"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="计量单位" align="center" width="100">
          <template slot-scope="scope">
            <el-select
              filterable
              style="width: 100%"
              v-model="scope.row.measureUnit"
              placeholder="请选择">
              <el-option
                v-for="item in measuringUnit"
                :key="item"
                :value="item"
                :label="item"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="120" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.buyNum"  controls-position="right" style="width: 100%" :min="0"  @change="calcGoodsTotal(scope.row)"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.unitPrice"  controls-position="right" :precision="2" :step="0.1" style="width: 100%" :min="0" @change="calcGoodsTotal(scope.row)"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="总价" prop="amount" align="center" width="100">
        </el-table-column>
        </el-table-column>
      </el-table>
      <div style="text-align: right; margin-top: 10px">
        <el-link type="primary" :underline="false" @click="addGoods">
          <el-button icon="el-icon-plus" type="primary" circle>
          </el-button>
          添加商品行
        </el-link>
      </div>
      <div style="margin-top:20px;text-align: right">
        <el-checkbox v-model="baseForm.createReceipt">同时创建收据</el-checkbox>
        <el-button
          v-if="title!='查看'"
          style="margin-left: 10px"
          @click="restForm"
          v-repeatClick
        >重置</el-button>
        <el-button
          v-if="title!='查看'"
          type="primary"
          style="margin-left: 10px"
          @click="submit"
          v-repeatClick
        >保存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'

let search = {
  //客户号
  customerNum:'',
  //销售单号,备注,物品内容
  info:'',
  //证件状态
  orderStatus:'',
  //时间范围
  date:[]
};


let baseForm = {
  id:0,
  //是否同时创建收据
  createReceipt:true,
  //客户号
  customerNum:'',
  //商品总金额
  goodsAmount:0,
  //销售单号
  orderCode:'',
  //状态
  orderStatus:'',
  //其他费用
  otherAmount:0,
  //总费用
  totalAmount:0,
  //门店名称
  storeName:'',
  //备注
  note:'',
  //收据编码
  receiptCode:'',
  //收据状态
  receiptStatus:'',
};

let orderGoodsForm = {
  id:0,
  //货物英文品牌
  goodsEnglishBrand:'',
  //商品类型
  goodsCategory:'包邮商品',
  userAdded:false,
  //货物名称
  goodsName:'',
  //货物类型id
  goodsType:'',
  //货物类型名称
  goodsTypeName:'',
  //规格型号
  specification:'',
  //计量单位
  measureUnit:'',
  //数量
  buyNum:'',
  //单价
  unitPrice:'0.00',
  //总价
  amount:'0',
  //待选货物列表
  goodsList:[]
}

import {
  getWorkworderGoods,
} from '@/api/business/waybill'
import myHeader from "@/components/pageHEader/pageHeader";
import { dateFormat } from "@/utils";
import {
  getSaleOrder,
  addSaleOrder,
  delSaleOrder,
  modSaleOrder,
  getSaleOrderGoods,
  getSaleOrderCode,
  getSaleOrderById
} from "@/api/business/sale";

import domMessage from '@/utils/messageOnce'
const messageOnce = new domMessage()
export default {
  name: "sale",
  components: {
    myHeader,
  },
  computed: {
    ...mapGetters(["stores"]),
  },
  data() {
    return {
      pageSize: 20,
      currentPage: 1,
      total: 0,
      data: [],
      //表格选中
      multipleSelection: [],
      //搜索
      search: this.cloneObj(search),
      //对话框
      dialogFormVisible: false,
      title: "添加",
      baseForm: this.cloneObj(baseForm),
      orderGoods:[],
      baseRules: {
        customerNum:[this.$RegExp.required()],
        orderStatus:[this.$RegExp.required('状态不能为空')]
      },
      baseFormOptions:{
        orderStatus:['未入账','已入账']
      },
    };
  },
  mounted() {
    this.getSaleOrder();
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val;
      this.getSaleOrder()
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getSaleOrder()
    },

    //重置表单信息
    restForm() {
      this.$nextTick(() => {
        if (this.$refs.baseForm) this.$refs.baseForm.resetFields();
      });
    },
    handleBeforeUpdate(){
      if (!this.multipleSelection.length) {
        this.tip();
        return;
      }
      if (this.multipleSelection.length > 1) {
        this.tip("只能勾选表格中的一条数据");
        return;
      }
      this.handleAddUpdate(this.multipleSelection[0])
    },
    handleAddUpdate(row) {
      this.activeName = "baseForm";
      //修改处理
      if (row) {
        this.title = "修改";
        getSaleOrderById(row.saleOrder.id).then(resp=>{
          let row = resp.data
          //将数据复制给form
          this.handleModform(row.saleOrder, this.baseForm);
          this.orderGoods = this.cloneObj(row.orderGoods)
          this.dialogFormVisible = true;
        })
      } else {
        this.title = "添加";
        getSaleOrderCode().then(resp=>{
          this.baseForm = this.cloneObj(baseForm);
          this.baseForm.orderCode = resp.msg
          this.orderGoods = []
          this.dialogFormVisible = true;
        })
      }
    },
    getSaleOrder() {
      let query = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        customerNum:this.search.customerNum,
        info:this.search.info,
        orderStatus:this.search.orderStatus,
        startTime: this.search.date[0]?this.search.date[0]+' 00:00:00':'',
        endTime: this.search.date[1]?this.search.date[1]+' 23:59:59':'',
      };
      getSaleOrder(query).then((resp) => {
        this.data =  resp.data.records
        this.total = resp.data.total;
      });
    },
    //表格双击修改
    handleRowDbclick(row) {
      this.handleAddUpdate(row);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    submit() {
      this.$refs["baseForm"].validate((valid) => {
        if (valid) {
          let orderGoods = this.cloneObj(this.orderGoods)
          orderGoods.forEach(item=>{
            delete item.goodsList
          })
          let submit = Object.assign({},
            {saleOrder:this.baseForm,orderGoods}
          );
          let request;
          if (this.title == "添加") {
            request = addSaleOrder(submit);
          } else {
            request = modSaleOrder(submit);
          }
          request.then((resp) => {
            this.$message.success(resp.message || "成功");
            this.dialogFormVisible = false;
            this.getSaleOrder();
          });
        } else {
          this.activeName = "baseForm";
        }
      });
    },
    //查看信息
    view() {
      this.handleBeforeUpdate();
      this.title = '查看';
    },
    //创建收据
    handleCreateInvoice(){
      if (!this.multipleSelection.length) {
        this.tip();
        return;
      }
      if(this.multipleSelection.some(item=>item.saleOrder.receiptCode)){
        this.tip('勾选的销售单不能包含已有收据信息的销售单');
        return;
      }
      let list = this.multipleSelection.map(item=>item.saleOrder.orderCode).join(',')
      this.$router.push({path:'/finances/invoice',query:{list}})
    },
    //删除信息
    delSaleOrder() {
      if (!this.multipleSelection.length) {
        this.tip();
        return;
      }
      this.confirm().then(() => {
        delSaleOrder(this.multipleSelection.map((item) => item.saleOrder.id)).then(
          (resp) => {
            this.$message.success(resp.message || "成功");
            this.getSaleOrder();
          }
        );
      });
    },
    deleteGoods(index) {
      this.confirm().then(() => {
        this.orderGoods.splice(index, 1);
      });
    },
    //添加商品行
    addGoods(){
      this.orderGoods.push(this.cloneObj(orderGoodsForm))
    },
    //商品条目改变时
    handleGoodsCategory(row){
      let goodsCategory = row.goodsCategory
      Object.assign(row,orderGoodsForm)
      row.goodsCategory = goodsCategory
    },
    //商品类型改变时 重新获取商品
    handleGoodsTypeChange(row){
      getSaleOrderGoods({goodsCategory:row.goodsCategory}).then(resp=>{
        this.$set(row,'goodsList',resp.data)
      })
    },
    //商品改变时 赋值
    handleGoodsChange(row){
      let goods = row.goodsList.filter(item=>item.englishBrand == row.goodsEnglishBrand)[0]
      if(goods){
        row.goodsName = goods.goodsName
        row.goodsType = goods.goodsType
        row.goodsTypeName = goods.goodsTypeName
        row.specification = goods.specification
        row.measureUnit = goods.measureUnit
        row.buyNum = 1
        row.unitPrice = parseFloat(this.oninput(goods.unitPrice))
        this.calcGoodsTotal(row)
      }else{
        row.userAdded = true
        row.goodsTypeName = '新增商品'
        row.goodsType = 0
      }
    },
    calcGoodsTotal(row){
      row.amount = this.oninput(parseFloat(row.buyNum)*parseFloat(row.unitPrice))
      this.calcAmount()
    },
    calcAmount(){
      let amount = this.orderGoods.map(item=>parseFloat(item.amount))
      if(amount.length){
        if(amount.length === 1){
          this.baseForm.goodsAmount = amount[0]
        }else{
          this.baseForm.goodsAmount = amount.reduce((a,b)=>a+b)
        }
        this.baseForm.totalAmount = parseFloat(this.baseForm.otherAmount) + this.baseForm.goodsAmount
      }
    },
    //计算 总费用
    handleOtherAmount(val){
      if(val){
        this.calcAmount()
        this.baseForm.totalAmount = parseFloat(val) + this.baseForm.goodsAmount
      }else{
        this.calcAmount()
        this.baseForm.totalAmount = this.baseForm.goodsAmount
      }
    }
  },
};
</script>

<style lang="scss" scoped>
@import "../../styles/_themeify";
@import "../../styles/mobile.scss";

.goods-item {
  line-height: 25px;
  span {
    margin-right: 10px;
  }
}

.cell-item {
  line-height: 30px;
}

// 移动端优化
@media screen and (max-width: 768px) {
  .el-dialog {
    .el-form {
      .el-row {
        .el-col {
          width: 100% !important;
          margin-bottom: 10px;
        }
      }
      
      .el-form-item {
        margin-bottom: 10px;
        
        .el-form-item__label {
          float: none;
          text-align: left;
          padding: 0 0 5px;
        }
        
        .el-form-item__content {
          margin-left: 0 !important;
        }
      }
      
      .el-input, .el-select {
        width: 100%;
      }
    }
    
    .el-table {
      /deep/ .el-table__row {
        td {
          padding: 5px !important;
        }
      }
    }
  }
}
</style>
